const _path = require('path')
const _fs = require('fs')
const PSD = require('../src/psd')
// console.log(PSD)
// for (let k in PSD) {
//     console.log(k, PSD[k])
// }
PSD.open('/Users/x/Desktop/ddd.psd').then(res => {
  // console.log(res)
  const data = res.tree()
  makeNodeFromPSD(data)
}).catch(e => {
  console.log('e: ', e)
})

const computeFontSize = (size, yy) => {
  if (yy !== 1) {
    return Math.round((size * yy) * 100) * 0.01
  } else { // transform.yy为1时，sizes[0]的值就是字体显示大小的值，不需要计算
    return size
  }
}
const arrToRgba = (arr) => {
  return `rgba(${arr[0]},${arr[1]},${arr[2]},${(arr[3] / 255.0).toFixed(2)})`
}
const checkIsSame = (font) => {
  const arr = ['styles', 'weights', 'sizes', 'colors', 'textDecoration']
  return arr.every(k => {
    let first = font[k][0]
    if (typeof first === 'object') {
      first = JSON.stringify(first)
    }
    return font[k].every(v => {
      const p = typeof v === 'object' ? JSON.stringify(v) : v
      return p === first
    })
  })
}

const JSONStringifySafe = (obj) => {
  let cache = []
  const str = JSON.stringify(obj, function (key, value) {
    if (typeof value === 'object' && value !== null) {
      if (cache.indexOf(value) !== -1) {
        return// 移除
      }
      cache.push(value)// 收集所有的值
    }

    if (typeof value === 'object' && value && Object.keys(value).length > 500) {
      return
    }

    if (/[a-zA-Z]+/g.test(key) && typeof value !== 'object') {
      // console.log('key: ', key, value)
    }
    return value
  })
  cache = null
  return str
}

const makeNodeFromPSD = async (data, px = 0, py = 0) => {
  // if (data.name === '组AAABBB') {
  //     console.log('组AAABBB: ', data.layer.blendMode, data.height)
  // }

  // console.log('parsed: ', parsed)
  // if (data.name === '图层 3247') {
  //     console.log('图层 3247: ', data.layer.blendMode, data.height)
  // }
  if (data.visible() === false) {
    return
  }
  if (!data.isRoot()) {
    data.toCss()
    const parsed = data.export()
    const sss = JSONStringifySafe(data)
    _fs.writeFileSync(_path.join(__dirname, 'ttt.json'), sss)
    // console.log('data.layer.adjustments.objectEffects: ', data.layer?.adjustments?.objectEffects?.layer.export())
  }

  // if (data.layer.typeTool) {
  //   console.log('TXT: ', parsed, parsed.text.font)
  //   const txt = parsed.text.value
  //   const font = parsed.text.font
  //   const yy = parsed.text.transform.yy
  //   const fonts = {
  //     family: font.names.join(),
  //     align: font.alignment[0],
  //     size: computeFontSize(font.sizes[0], yy),
  //     sizeUtil: 'px',
  //     color: arrToRgba(font.colors[0]),
  //     isB: font.weights[0] === 'bold',
  //     isI: font.styles[0] === 'italic',
  //     isU: font.textDecoration[0] === 'underline'
  //   }
  //   let str = `<span>${txt}</span>`
  //   if (font.lengthArray.length > 1 && !checkIsSame(font)) {
  //     str = ''
  //     let i = 0
  //     font.lengthArray.forEach((length, index) => {
  //       const sub = txt.slice(i, i + length)
  //       i += length
  //       const subFonts = {
  //         size: computeFontSize(font.sizes[index], yy),
  //         color: arrToRgba(font.colors[index]),
  //         isB: font.weights[index] === 'bold',
  //         isI: font.styles[index] === 'italic',
  //         isU: font.textDecoration[index] === 'underline'
  //       }
  //       const css = {}
  //       if (subFonts.size) css['font-size'] = subFonts.size + 'px'
  //       if (subFonts.color) css.color = subFonts.color
  //       if (subFonts.isB) css['font-weight'] = subFonts.isB ? 600 : 400
  //       if (subFonts.isI) css['font-style'] = subFonts.isI ? 'italic' : 'normal'
  //       if (subFonts.isU) css['text-decoration'] = subFonts.isU ? 'underline' : 'unset'
  //       let cssStr = ''
  //       for (const k in css) {
  //         const v = `${css[k]}`.trim()
  //         cssStr += k + ':' + v + ';'
  //       }
  //       str += `<span style="${cssStr}">${sub}</span>`
  //     })
  //   }
  //
  //   const transform = `transform: matrix(${parsed.text.transform.xx},0,0,${parsed.text.transform.yy},0,0);`
  //   console.log('transform: ', transform)
  //   str += `<p style="${transform}">${str}</p>`
  //   console.log('str: ', str)
  //
  //   // console.log('图层 3293 11: ', data.layer.node.clippingMask())
  // }

  const w = data.width
  const h = data.height

  const css = {
    width: w,
    height: h,
    top: data.top - py,
    left: data.left - px
  }
  if (
    !data.isGroup() &&
        data.width > 0 &&
        data.height > 0 &&
        data.layer.image
  ) {
    // console.log('data.layer.image: ', data.layer.image.toBase64, data.layer.image.toPng)
    // console.log(data.layer.image.toPng())
    const image = await data.layer.image.toBase64()
    // console.log('image: ', image.length)
    css.bg = {
      type: 'image',
      image: {
        path: image,
        px: 50,
        py: 50,
        repeat: {
          repeat: 'no-repeat',
          size: 'auto'
        }
      }
    }
  }
  if (data._children) {
    const childs = data._children
    for (const layer of [...childs].reverse()) {
      makeNodeFromPSD(layer, data.left, data.top)
    }
  }
}
